﻿@page "/DataSource/TaskConfig"
@using OnWork.DataCenter.BLL.DataCenter;
@using OnWork.DataCenter.DAL.DataCenter;
@using OnWork.DataCenter.Shared.Common;
@using OnWork.DataCenter.BLL.Standard;
@using Newtonsoft.Json;
<PageTitle>定时任务配置</PageTitle>
@inherits ComponentBaseDataCenter
<div>
    <h3>定时任务配置</h3>

    <Table @ref="table" TItem="TaskConfigVO" UseInjectDataService="false" IsPagination="true" DoubleClickToEdit="true"
           IsStriped="true" IsBordered="true" ShowSkeleton="true" IsMultipleSelect="true" ShowEmpty="true" ShowLoading="true" ShowColumnList="true"
           ShowToolbar="true" ShowExtendButtons="true"
           ShowSearch="true" ShowAdvancedSearch="false"
           AutoGenerateColumns="true" EditMode="EditMode.Popup"
           OnQueryAsync="@QueryAsync" OnSaveAsync="@OnSaveAsync" OnDeleteAsync="OnDeleteAsync" ShowToastAfterSaveOrDeleteModel="false">
        <RowButtonTemplate>
            <TableCellButton Color="Color.Info" Icon="fa-solid fa-pen" Text="流程测试" OnClick="@(()=>OnTestAsync(context))" IsAsync="true" />
            @*<TableCellPopconfirmButton Color="Color.Info" Icon="fa-solid fa-pen" Text="测试" />*@
        </RowButtonTemplate>
        <TableToolbarTemplate>
            <TableToolbarButton Color="Color.Info" Icon="fas fa-copy" TItem="TaskConfigVO" Text="复制" IsAsync OnClickCallback="@CopyItemsAsync" />
             <TableToolbarButton TItem="TaskConfigVO" Text="启用" IsAsync OnClickCallback="@(x=>{return EnableItemsAsync(x,true);})" />
             <TableToolbarButton Color="Color.Secondary" TItem="TaskConfigVO" Text="禁用" IsAsync OnClickCallback="@(x=>{return EnableItemsAsync(x,false);})" />
         </TableToolbarTemplate>
         <EditTemplate>
             <TaskConfigEditView Config="@context" />
         </EditTemplate>
     </Table>
 </div>

    @code {
    /// <summary>
    /// 依赖注入 提示信息
    /// </summary>
    [Inject]
    protected DSTaskBLL dBConnBLL { get; set; }

    /// <summary>
    /// 后台任务
    /// </summary>
    [Inject]
    private OnWork.DataCenter.BLL.TaskScheduler.TaskSchedulerBLL taskSchedulerBLL { get; set; }

    /// <summary>
    /// 当前表格
    /// </summary>
    private Table<TaskConfigVO> table;
    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="options"></param>
    /// <returns></returns>
    private async Task<QueryData<TaskConfigVO>> QueryAsync(QueryPageOptions options)
    {
        var result = await dBConnBLL.QueryPagedListAsync(options.ToBaseQueryPageInput());
        //对象转换
        return result.ToQueryData<TaskConfigVO, DSTask>();
    }

    /// <summary>
    /// 删除数据
    /// </summary>
    /// <param name="items"></param>
    /// <returns></returns>
    private async Task<bool> OnDeleteAsync(IEnumerable<TaskConfigVO> item)
    {
        var result = await dBConnBLL.DeleteDataAsync(item.Select(x => x.ID).ToArray());
        await taskSchedulerBLL.UpdateJobs();
        return await ShowSqlReturnMsg(result);
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <param name="item"></param>
    /// <param name="changedType"></param>
    /// <returns></returns>
    private async Task<bool> OnSaveAsync(TaskConfigVO item, ItemChangedType changedType)
    {
        //RESTfulResult<object> result;
        if (changedType == ItemChangedType.Update) // 更新
        {
            var result = await dBConnBLL.UpdateDataAsync(item.Adapt<DSTask>());
            await taskSchedulerBLL.UpdateJobs();
            return await ShowSqlReturnMsg(result);
        }
        else //新增
        {
            var result = await dBConnBLL.AddDataAsync(item.Adapt<DSTask>());
            await taskSchedulerBLL.UpdateJobs();
            return await ShowSqlReturnMsg(result);
        }
    }


    /// <summary>
    /// 连接测试
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    private async Task OnTestAsync(TaskConfigVO item)
    {
        try
        {
            //流程配置
            var config = item.TaskConfigView;

            if (!string.IsNullOrEmpty(config))
            {
                var dto = JsonConvert.DeserializeObject<List<DataStandardTreeDto>>(config);
                if (dto != null)
                {
                    StandardConvert.ProcessTreeStandards(dto);
                    await ToastService?.Success("流程测试", "已经执行流程!");
                    return;
                }

            }
            await ToastService?.Error("流程测试", "配置出错!");
        }
        catch (Exception ex)
        {
            await base.MessageError(ex.ToString());
            //throw;
        }
    }

    /// <summary>
    /// 复制多个对象
    /// </summary>
    /// <param name="items"></param>
    /// <returns></returns>
    private async Task CopyItemsAsync(IEnumerable<TaskConfigVO> items)
    {
        if (items.Count() > 0)
        {
            var result = await dBConnBLL.CopyDataAsync(items.Adapt<List<DSTask>>());
            await ShowSqlReturnMsg(result);
            await table.QueryAsync();
        }
    }

    /// <summary>
    /// 启用或禁用任务
    /// </summary>
    /// <param name="items"></param>
    /// <returns></returns>
    private async Task EnableItemsAsync(IEnumerable<TaskConfigVO> items,bool enable)
    {
        //获取需要更改的对象
        var updateItems = items.Where(x => x.Enable != enable).ToList();
        if (updateItems != null && updateItems.Count>0)
        {
            var item = updateItems.Adapt<List<DSTask>>();
            item.ForEach(x=>x.Enable=enable); //修改启用状态
            var result = await dBConnBLL.UpdateDataAsync(item);
            await taskSchedulerBLL.UpdateJobs(); //更新任务
            await ShowSqlReturnMsg(result);
            await table.QueryAsync();
        }else
        {
            await base.ToastService?.Error("发生错误","没有可更新的对象");
        }
    }
}
